#!/usr/bin/python3
#https://www.runoob.com/python3/python3-multithreading.html

#!/usr/bin/python3

import queue
import threading
import time
from datetime import datetime

def current_milliseconds():
   return "%03d" % (datetime.now().microsecond // 1000)

exitFlag = 0
threadLock = threading.Lock()

def current_milli_time():
    return round(time.time() * 1000)

def show(msg):
   threadLock.acquire()
   #print(time.strftime("%Y/%m/%d %H:%M:%S %j of 365", time.localtime()), current_milli_time(), current_milliseconds(),time.time_ns(),  msg)
   print(time.strftime("%Y/%m/%d %H:%M:%S", time.localtime()) + '.' + current_milliseconds(), msg)
   threadLock.release()

class myThread (threading.Thread):
    def __init__(self, threadID, name, q):
        threading.Thread.__init__(self)
        self.threadID = threadID
        self.name = name
        self.q = q
    def run(self):
        show ("Start thread: " + self.name)
        process_data(self.name, self.q)
        show ("Exit thread: " + self.name)

def process_data(threadName, q):
    while not exitFlag:
        queueLock.acquire()
        if not workQueue.empty():
            data = q.get()
            queueLock.release()
            show ("Thread %s processing %s." % (threadName, data))
        else:
            queueLock.release()
        time.sleep(1)

threadList = ["Thread-1", "Thread-2", "Thread-3"]
nameList = ["One", "Two", "Three", "Four", "Five"]
queueLock = threading.Lock()
workQueue = queue.Queue(10)
threads = []
threadID = 1

# 创建新线程
for tName in threadList:
    thread = myThread(threadID, tName, workQueue)
    thread.start()
    threads.append(thread)
    threadID += 1

# 填充队列
queueLock.acquire()
for word in nameList:
    workQueue.put(word)
queueLock.release()

# 等待队列清空
while not workQueue.empty():
    pass

# 通知线程是时候退出
exitFlag = 1

# 等待所有线程完成
show('threads.join()')
for t in threads:
    t.join()

while(True):
    show("waiting...")
    time.sleep(0.1)

show("Exited.")